package com.snailct.bpp.commons.xom.castor;

import com.snailct.bpp.commons.xom.XOMTransformer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Component;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by Administrator on 2016/9/20 0020.
 */
@Component("xomTransformerReader")
public class XOMTransformerReader implements XOMTransformer {
    @Autowired
    @Qualifier("marshaller")
    private Marshaller marshaller;
    @Autowired
    @Qualifier("marshaller")
    private Unmarshaller unmarshaller;
    public String marshal(Object object) throws IOException {
        if(object==null) return null;
        StringWriter stringWriter = new StringWriter();
        this.marshaller.marshal(object,new StreamResult(stringWriter));
        return stringWriter.toString();
    }

    public Object unMarshal(String xml) throws IOException {
        if(StringUtils.isEmpty(xml)) return xml;
        StringReader reader = new StringReader(xml);
        return this.unmarshaller.unmarshal(new StreamSource(reader));
    }

}
